package org.ishequ.weibo.adapater;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.ishequ.miduo.R;
import org.ishequ.miduo.weibo.WeiboHomeActivity;
import org.ishequ.miduo.MiDuoActivity.ConfigHelper;
import org.ishequ.weibo.utils.DateUtilsDef;
import org.ishequ.weibo.utils.http.AsyncImageLoader;
import org.ishequ.widget.AutoGetMoreListView;
import org.ishequ.widget.HighLightTextView;
import org.ishequ.widget.OnGetMoreListener;
import org.ishequ.widget.OnRefreshListener;

import weibo4android.Comment;
import weibo4android.Paging;
import weibo4android.Status;
import weibo4android.Weibo;
import weibo4android.WeiboException;
import weibo4android.WeiboResponse;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

// 微博列表Adapater
public class WeiboAdapter extends BaseAdapter 
							implements OnRefreshListener,OnGetMoreListener{
	
	private List<WeiboResponse> wbList;
	private int resource;
	private LayoutInflater inflater;
	private AutoGetMoreListView autoGetMoreListView;
	
	private Context context;

	private AsyncImageLoader asyncImageLoader;
	private int type; 	// 0 for 收到的评论  1 for 发出的评论  2 for @我  3 for 微博
	private String cid; // 代表当前查看的是指定人的微博	
	
	public WeiboAdapter(Context context,int resource,List<WeiboResponse> wbList,int type,AutoGetMoreListView autoGetMoreListView) {
		this.wbList = wbList;
		this.resource = resource;
		this.type = type;
		this.autoGetMoreListView = autoGetMoreListView;
		this.context = context;
		this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public int getCount() {
		return wbList.size();
	}

	@Override
	public Object getItem(int position) {
		return wbList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		asyncImageLoader = new AsyncImageLoader();
		convertView = inflater.inflate(resource, null);
		bindView(position ,convertView);
		return convertView;
	}
	
	private void bindView(int position,View convertView){
		WeiBoHolder wh = new WeiBoHolder();
		wh.wbicon = (ImageView) convertView.findViewById(R.id.wbicon);
		wh.wbtext = (HighLightTextView) convertView.findViewById(R.id.wbtext);
		wh.wbtime = (TextView) convertView.findViewById(R.id.wbtime);
		wh.wbuser = (TextView) convertView.findViewById(R.id.wbuser);
		wh.wbimage = (ImageView) convertView.findViewById(R.id.wbimage);
		
		String screenName = "";
		String userID = "";	
		String time = "";
		String icon_url = "";	
		
		switch (type) {
		case 0:
		case 1:
			Comment comment = (Comment) wbList.get(position);
			userID = comment.getUser().getId() + "";
			String commentText = comment.getText();
			if (comment.getReplyComment() != null) {
				commentText = commentText
						+ "\n\n回复@"
						+ comment.getReplyComment().getUser()
								.getScreenName() + " 的评论: "
						+ comment.getReplyComment().getText();

				if (comment.getStatus() != null)
					commentText = commentText + "\n\n原微博是: @"
							+ comment.getStatus().getUser().getScreenName()
							+ ": " + comment.getStatus().getText();

				if (comment.getStatus().getRetweeted_status() != null)
					commentText = commentText
							+ "\n转自: @"
							+ comment.getStatus().getRetweeted_status()
									.getUser().getScreenName()
							+ ": "
							+ comment.getStatus().getRetweeted_status()
									.getText();

			} else if (comment.getStatus() != null) {
				commentText = commentText + "\n\n评论@"
						+ comment.getStatus().getUser().getScreenName()
						+ " 的微博: " + comment.getStatus().getText();

				if (comment.getStatus().getRetweeted_status() != null)
					commentText = commentText
							+ "\n转自: @"
							+ comment.getStatus().getRetweeted_status()
									.getUser().getScreenName()
							+ ": "
							+ comment.getStatus().getRetweeted_status()
									.getText();
			}

			if (comment.getStatus() != null) {
				if (comment.getStatus().getRetweeted_status() != null) {
					if (!TextUtils.isEmpty(comment.getStatus().getRetweeted_status().getThumbnail_pic()))
						wh.wbimage.setVisibility(View.VISIBLE);
				} else if (!TextUtils.isEmpty(comment.getStatus().getThumbnail_pic())) {
					wh.wbimage.setVisibility(View.VISIBLE);
				}
			}

			wh.wbtext.setText(commentText);
			icon_url = comment.getUser().getProfileImageURL()
					.toString();
			time = comment.getCreatedAt().toString();
			screenName = comment.getUser().getScreenName();
			break;

		case 2:
		case 3:
			Status wb = (Status)wbList.get(position);
			time = wb.getCreatedAt().toString();
			icon_url = wb.getUser().getProfileImageURL().toString();
//			convertView.setTag(wb.getId());
			wh.wbuser.setText(wb.getUser().getName());
			
			userID = wb.getUser().getId() + "";

			String text = wb.getText();
			if (wb.getRetweeted_status() != null)
				text = text
						+ "\n\n转自: @"
						+ wb.getRetweeted_status().getUser()
								.getScreenName() + " :"
						+ wb.getRetweeted_status().getText();
			wh.wbtext.setText(text);
			screenName = wb.getUser().getScreenName();

			if (wb.getRetweeted_status() != null) {
				if (!TextUtils.isEmpty(wb.getRetweeted_status().getThumbnail_pic()))
					wh.wbimage.setVisibility(View.VISIBLE);
				} else if (!TextUtils.isEmpty(wb.getThumbnail_pic()))
					wh.wbimage.setVisibility(View.VISIBLE);
			
			break;
		}
		
		Date startDate=new Date(time);
        Date nowDate = Calendar.getInstance().getTime();
        time = new DateUtilsDef().twoDateDistance(startDate,nowDate);
        if(time == null || "".equals(time)) time = "0分钟";
		wh.wbtime.setText(time + " 前");
		
		if (false) {
			// wh.wbimage.setImageResource(R.draw.able.images);
		}
		Drawable cachedImage = asyncImageLoader.loadDrawable(icon_url, wh.wbicon,
				new AsyncImageLoader.ImageCallback() {

					@Override
					public void imageLoaded(Drawable imageDrawable,
							ImageView imageView, String imageUrl) {
						imageView.setImageDrawable(imageDrawable);
					}

				});
		if (cachedImage == null) {
			wh.wbicon.setImageResource(R.drawable.weibo_avatar);
		} else {
			wh.wbicon.setImageDrawable(cachedImage);
		}
		
	}
	
	public class WeiBoHolder {
		public ImageView wbimage;
		public ImageView wbicon;
		public TextView wbuser;
		public TextView wbtime;
		public HighLightTextView wbtext;
	}

	@Override
	public void onRefresh() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				Weibo weibo = new Weibo();
				weibo.setToken(ConfigHelper.nowUser.getToken(), ConfigHelper.nowUser.getTokenSecret());
				NotificationManager notificationManager = (NotificationManager) context
						.getSystemService(Context.NOTIFICATION_SERVICE);
				try {
					switch (type) {
						case 0:
							List<Comment> newCommentToMe = weibo.getCommentsToMe();
							wbList.clear();
							wbList.addAll(newCommentToMe);
							notificationManager.cancel(WeiboHomeActivity.UNREAD_COMMENT);
							weibo.resetCount(1);
							break;

						case 1:
							List<Comment> newCommentByMe = weibo.getCommentsByMe();
							wbList.clear();
							wbList.addAll(newCommentByMe);
							break;

						case 2:
							List<Status> newMentions = weibo.getMentions();
							wbList.clear();
							wbList.addAll(newMentions);

							notificationManager
									.cancel(WeiboHomeActivity.UNREAD_MENTION);
							weibo.resetCount(2);
							break;

						case 3:
							List<Status> newTimeline;
							if (TextUtils.isEmpty(cid))
								newTimeline = weibo.getFriendsTimeline();
							else
								newTimeline = weibo.getUserTimeline(cid);
							wbList.clear();
							wbList.addAll(newTimeline);
							break;
					}
				} catch (WeiboException e) {
					e.printStackTrace();
				}
				autoGetMoreListView.refreshFinished();
			}
		}).start();
	}

	@Override
	public void onGetMore() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				Paging paging = new Paging(2);
				if (wbList.size() > 0) {
					Weibo weibo = new Weibo();
					weibo.setToken(ConfigHelper.nowUser.getToken(), ConfigHelper.nowUser.getTokenSecret());
					try {
						switch (type) {
						case 0:
							paging.setMaxId(((Comment) wbList.get(wbList
									.size() - 1)).getId());
							wbList.addAll(weibo.getCommentsToMe(paging));
							break;

						case 1:
							paging.setMaxId(((Comment) wbList.get(wbList
									.size() - 1)).getId());
							wbList.addAll(weibo.getCommentsByMe(paging));
							break;

						case 2:
							paging.setMaxId(((Status) wbList.get(wbList
									.size() - 1)).getId());
							wbList.addAll(weibo.getMentions(paging));
							break;

						case 3:
							paging.setMaxId(((Status) wbList.get(wbList
									.size() - 1)).getId());
							if (TextUtils.isEmpty(cid))
								wbList.addAll(weibo
										.getFriendsTimeline(paging));
							else
								wbList.addAll(weibo.getUserTimeline(cid,
										paging));
							break;
					}
					} catch (WeiboException e) {
						e.printStackTrace();
					}
				}
				autoGetMoreListView.getMoreFinished();
			}
		}).start();
	}
	
	public List<WeiboResponse> getWbList() {
		return wbList;
	}

	public void setWbList(List<WeiboResponse> wbList) {
		this.wbList = wbList;
	}

	public int getType() {
		return type;
	}

	public void setType(int type) {
		this.type = type;
	}

	public void setCid(String cid) {
		this.cid = cid;
	}
	
}